﻿using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Runtime;
using Autodesk.Windows;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;


[assembly: ExtensionApplication(typeof(SEPD.CAD.Template.Ribbon.AcadNetApp))]
namespace SEPD.CAD.Template.Ribbon
{
    public class AcadNetApp : IExtensionApplication
    {
        public static string assemblyPath = Assembly.GetExecutingAssembly().Location;
        public static string assemblyDir = Path.GetDirectoryName(assemblyPath) + "\\";

        //Assembly assemblyPrismBas = Assembly.LoadFrom($"{assemblyDir}Prism.dll");
        //Assembly assemblyPrismWpf = Assembly.LoadFrom($"{assemblyDir}Prism.Wpf.dll");
        //Assembly assemblyInteract = Assembly.LoadFrom($"{assemblyDir}System.Windows.Interactivity.dll");

        /// <summary>
        /// 启动动作
        /// </summary>
        public void Initialize()
        {
            RibbonService.AddEnv(assemblyDir);

            Application.Idle += OnIdle;
            //需要添加事件，监听工作空间有没有变化，如果有变化，需要重新生成面板
            Application.SystemVariableChanged += new SystemVariableChangedEventHandler(Application_SystemVariableChanged);

        }

        /// <summary>
        /// 关闭动作
        /// </summary>
        public void Terminate()
        {
            // do somehing to cleanup resource 
            Application.Idle -= OnIdle;
            //卸载
            Application.SystemVariableChanged -= new SystemVariableChangedEventHandler(Application_SystemVariableChanged);

        }

        /// <summary>
        /// 启动时行为
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnIdle(object sender, EventArgs e)
        {
            //无论如何 刷新一下工作空间
            var wsCurrent = Application.GetSystemVariable("WSCURRENT");
            Application.SetSystemVariable("WSCURRENT", wsCurrent);

            Application.Idle -= OnIdle;
        }

        /// <summary>
        /// 监听动作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Application_SystemVariableChanged(object sender, SystemVariableChangedEventArgs e)
        {
            //Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            //ed.WriteMessage("\n-Sys Var Changed: " + e.Name);

            if (e.Name.ToLower() == "wscurrent")
            {
                Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("\n加载程序中...\n");
                AddRibbon();
                Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("\n加载程序完成\n");
            }
        }

        //==========================================================================================================

        /// <summary>
        /// 需要添加的Ribbon界面内容
        /// </summary>
        public void AddRibbon()
        {
            RibbonControl ribbonControl = ComponentManager.Ribbon;
            //该步骤自动时可能加载卡住
            RibbonTab ribbonTab = ribbonControl.AddTab("ribbonTab", Guid.NewGuid().ToString(), true);
            RibbonPanelSource panelSource = ribbonTab.AddPanel("ribbonAutoPanel");

            //----- 
            //调用CAD内部命令 Line
            RibbonButton lineButton =
            RibbonService.GenRibbonButton("Line_TEST", "Line_Text", "Line",
                new RibbonCommandHandler(),
                             RibbonService.GenImageSource(Resource.ICON_ALL));
            panelSource.Items.Add(lineButton); 
            //----- 
           
            ////按下按钮时加载指定dll内功能
            //var dllPath = Path.Combine(assemblyDir, "CAD.Demo.dll");
            //if (!File.Exists(dllPath))
            //{ 
            //    RibbonButton ribbonButton =
            //        RibbonService.GenRibbonButton("LoadDll_TEST", "LoadDll_TEXT", " ",
            //          new LoadDllCommandHandler(dllPath, "CAD.Demo.HelloCommand", "ShowWpfView"),
            //                       RibbonService.GenImageSource(Resource.ICON_ALL));
            //    panelSource.Items.Add(ribbonButton);
            //}

            //-----------------------------------------------------------------------

            /* 
             * json 结构参考
             {
                  "buttonName":"BTNJSON",
                  "buttonDescription":"CAD-DEMO-HELLO",
                  "dllName": "CAD.Demo.dll",
                  "namespaceName": "CAD.Demo",
                  "className": "HelloCommand",
                  "methodName": "CadDbText"
             } 
             */
            // 记得把所有需要ribbon加载为按钮的json都放在安装根目录的_signature_文件夹下
            // 而功能DLL需要和Ribbon类同目录


            var buttonRegisterDir = $"{assemblyDir}_signature_\\";
            if (Directory.Exists(buttonRegisterDir))
            {
                //通过json文档描述的DLL信息 利用反射方法预先做好按钮的命令接口
                List<RibbonButton> ribbonButtons = new List<RibbonButton>();
                var jsonFiles = Directory.GetFiles($"{assemblyDir}_signature_\\")
                    .Where(f => f.Contains(".json"))
                    .ToList();

                List<CommandInfo> commandInfos = new List<CommandInfo>();
                //获得JSON描述的DLL信息
                foreach (var jsonFile in jsonFiles)
                {
                    if (!File.Exists(jsonFile)) { continue; }
                    string jsonStr = jsonFile.ReadJsonText(Encoding.UTF8);
                    CommandInfo cmdInfo = jsonStr.ToClassEntity<CommandInfo>().First();
                    //防止两次加载相同的方法
                    if (commandInfos
                        .Any(info =>
                                info.dllName == cmdInfo.dllName &&
                                info.namespaceName == cmdInfo.namespaceName &&
                                info.className == cmdInfo.className &&
                                info.methodName == cmdInfo.methodName
                    ))
                    { continue; }
                    commandInfos.Add(cmdInfo);
                }
                //构造反射结构给button
                foreach (var cmdInfo in commandInfos)
                {
                    string buttonName = cmdInfo.buttonName;
                    string buttonDescription = cmdInfo.buttonDescription;
                    string dllName = cmdInfo.dllName;
                    string namespaceName = cmdInfo.namespaceName;
                    string className = cmdInfo.className;
                    string methodName = cmdInfo.methodName;

                    var dllFilePath = $"{assemblyDir}{dllName}";
                    var namespaceClass = $"{namespaceName}.{className}";

                    if (!File.Exists(dllFilePath)) { continue; }

                    var command = new LoadDllCommandHandler(dllFilePath, namespaceClass, methodName);
                    var image = RibbonService.GenImageSource(Resource.ICON_ALL);
                    RibbonButton button = RibbonService.GenRibbonButton(buttonName, buttonDescription, " ", command, image);

                    ribbonButtons.Add(button);
                }

                //TODO 若需要修改部分按钮的详情可直接LINQ搜索获得实体并修改属性
                // ribbonButtons.Where (rb=>rb.Name=="BTN_NAME").ToList() .ForEach(rb => rb.Text = "BTN_TEXT");

                //放入panel
                ribbonButtons.ForEach(rb => panelSource.Items.Add(rb));


            }




        }
    }

}
